package com.xysq.activity;
/**
 * @Author huangdongkai
 */

import android.annotation.TargetApi;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.rockcent.action.CallbackListener;
import com.umeng.analytics.MobclickAgent;
import com.xysq.lemon.R;
import com.xysq.util.Base64;
import com.xysq.util.PropertiesUtil;
import com.xysq.util.ToastUtil;
import com.xysq.util.UserInfoKeeper;
import com.xysq.widget.ReleaseImageDialog;

import java.io.ByteArrayOutputStream;

import butterknife.InjectView;

public class IdentifyActivity extends BaseActivity implements View.OnClickListener,PopupWindow.OnDismissListener {
    @InjectView(R.id.img_add_picture)
    ImageView addPictureImg;
    @InjectView(R.id.ibtn_back)
    ImageButton backIbtn;
    @InjectView(R.id.btn_upload)
    Button uploadBtn;
    @InjectView(R.id.txt_message)
    TextView messageTxt;
    @InjectView(R.id.txt_info)
    TextView infoTxt;

    private Dialog releaseImageDialog = null;
    private ReleaseImageDialog.Builder releaseImageDialogBuilder;
    private Uri takePhotoUri;
    public static final int SELECT_PICTURE = 2;
    public static final int TAKE_PHOTO = 1;
    private static final double MAX_PIC_SIZE = 50;
    private String picUrl;
    private Bitmap bitmapPic;
    private String bitmapString;
    private String idnum = "";
    public static final String FAIL = "fail";
    private PopupWindow popupWindow;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_identify);
        initView();
    }

    //
    private void initView() {
        addPictureImg.setOnClickListener(this);
        backIbtn.setOnClickListener(this);
        uploadBtn.setOnClickListener(this);
        infoTxt.setOnClickListener(this);
        if (getIntent().getStringExtra(FAIL) != null && getIntent().getStringExtra(FAIL).equals(FAIL)) {
            uploadBtn.setText(getResources().getString(R.string.txt_upload_again));
            messageTxt.setText(getResources().getString(R.string.txt_fail_upload));
        }
    }

    @Override
    public void onClick(View view) {
        if (view == addPictureImg) {
            MobclickAgent.onEvent(this, "1033");
            createDialog();
            listenDialog();
            showReleaseImageDialog();
        }
        if (view == backIbtn) {
            finish();
        }
        if (view == uploadBtn) {
            if (TextUtils.isEmpty(UserInfoKeeper.readRealName(this))) {
                showPopupWindow();
            } else {
//            if(uploadBtn.equals(getResources().getString(R.string.upload))) {
                if (bitmapPic == null) {
                    ToastUtil.showShort(this, getResources().getString(R.string.toast_choice_pic));
                } else {
                    upload(bitmapString);
                }
            }
/*            } else {
                createDialog();
                listenDialog();
                showReleaseImageDialog();
            }*/
        }
        if(view == infoTxt) {
            startActivity(new Intent(this, UserActivity.class));
        }

    }

/*    //弹出购买成功券包
    private void showDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.dialog_need_realname);
        String sure = getResources().getString(R.string.dialog_go_realname);
        String cacle = getResources().getString(R.string.dialog_action_cancel);
        builder.setNegativeButton(cacle, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });
        builder.setPositiveButton(sure,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        startActivityForResult(new Intent(IdentifyActivity.this, UserActivity.class), UserActivity.IDENTIFY_CODE);
                        ToastUtil.showShort(IdentifyActivity.this, getResources().getString(R.string.toast_update_info));
                        dialog.dismiss();
                    }
                });
        builder.show();
    }*/

    private void showPopupWindow() {
        // 一个自定义的布局，作为显示的内容
        View contentView = LayoutInflater.from(this).inflate(
                R.layout.pop_identify, null);
        // 设置按钮的点击事件
        Button sureBtn = (Button) contentView.findViewById(R.id.btn_sure);
        Button cancleBtn = (Button) contentView.findViewById(R.id.btn_cancle);
        sureBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(IdentifyActivity.this, UserActivity.class));
                popupWindow.dismiss();
            }
        });
        cancleBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
        WindowManager wm = this.getWindowManager();
        int width = wm.getDefaultDisplay().getWidth();
        popupWindow = new PopupWindow(contentView,
                width - 100, LinearLayout.LayoutParams.WRAP_CONTENT, true);

        popupWindow.setTouchable(true);
//        changeBackground(0.7f);
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 0.5f;
        getWindow().setAttributes(lp);
        // 如果不设置PopupWindow的背景，无论是点击外部区域还是Back键都无法dismiss弹框
        // 我觉得这里是API的一个bug
        popupWindow.setBackgroundDrawable(getResources().getDrawable(
                R.drawable.black));
        popupWindow.setOnDismissListener(this);
        // 使其聚焦
        popupWindow.setFocusable(true);
        // 设置允许在外点击消失
        popupWindow.setOutsideTouchable(true);

        // 设置好参数之后再show
        popupWindow.showAtLocation(new View(this), Gravity.CENTER, 0, 0);
    }

    @Override
    public void onDismiss() {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 1f;
        getWindow().setAttributes(lp);
    }

    private void createDialog() {
        releaseImageDialogBuilder = new ReleaseImageDialog.Builder(this);
        releaseImageDialog = releaseImageDialogBuilder.create();
    }

    private void listenDialog() {
        releaseImageDialogBuilder.pictureButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                pictureChoose();
                releaseImageDialog.dismiss();
            }
        });
        releaseImageDialogBuilder.photoButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                pressTakePhotoButton();
                releaseImageDialog.dismiss();
            }
        });
        releaseImageDialogBuilder.cancleButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                releaseImageDialog.dismiss();
            }
        });
    }

    private void showReleaseImageDialog() {
        android.view.Window dialogWindow1 = releaseImageDialog.getWindow();
        WindowManager.LayoutParams lp1 = releaseImageDialog.getWindow().getAttributes();
        android.util.DisplayMetrics dm1 = new android.util.DisplayMetrics();
        this.getWindowManager().getDefaultDisplay().getMetrics(dm1);
        dialogWindow1.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL);
        releaseImageDialog.getWindow().setAttributes(lp1);
        releaseImageDialog.show();
    }

    private void pictureChoose() {
        Intent intent = new Intent();
        /* 开启Pictures画面Type设定为image */
        intent.setType("image/*");
        /* 使用Intent.ACTION_GET_CONTENT这个Action */
        intent.setAction(Intent.ACTION_GET_CONTENT);
        /* 取得相片后返回本画面 */
        startActivityForResult(intent, SELECT_PICTURE);
    }

    private void pressTakePhotoButton() {
        String status = Environment.getExternalStorageState();
        if (status.equals(Environment.MEDIA_MOUNTED)) {// 判断是否有SD卡
            takePhoto();
        } else {
            Toast.makeText(this, "没有SD卡", Toast.LENGTH_SHORT).show();
        }

        releaseImageDialog.dismiss();
    }

    private void takePhoto() {
        startActivityForResult(new Intent("android.media.action.IMAGE_CAPTURE"), TAKE_PHOTO);
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case SELECT_PICTURE:
                if (resultCode == this.RESULT_OK) {
                    Uri selectedImage = data.getData();
                    upLoadPhoto(selectedImage);
                }
                break;
            case TAKE_PHOTO:
                if (resultCode == this.RESULT_OK) {
//                    upLoadPhoto(takePhotoUri);
                    bitmapPic = (Bitmap) data.getExtras().get("data");
                    RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,RelativeLayout.LayoutParams.MATCH_PARENT);
                    addPictureImg.setLayoutParams(layoutParams);
                    addPictureImg.setImageBitmap(bitmapPic);//想图像显示在ImageView视图上，private ImageView img;
                 /*   File myCaptureFile = new File("sdcard/123456.jpg");
                    try {
                        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
      *//* 采用压缩转档方法 *//*
                        bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);
/
           *//* 调用flush()方法，更新BufferStream *//*
                        bos.flush();

           *//* 结束OutputStream *//*
                        bos.close();*/
                }
                break;
        }
    }

    private void upLoadPhoto(Uri selectedImage) {
        Log.d("test",Environment.getExternalStorageDirectory().getAbsolutePath());
        picUrl = selectedImage.toString();
        final Bitmap bitmap = imageZoom(getBitmapFromUri(selectedImage));
        Log.e("++++压缩后图片大小", bitmap.getByteCount() / 1024 + "");
        bitmapString = Base64.encode(bitmap2Bytes(bitmap));
        Log.e("++++编码大小", bitmapString.getBytes().length / 1024 + "");
        Log.d("test",selectedImage.toString());
        bitmapPic = getBitmapFromUri(selectedImage);
        new Thread(new Runnable() {
            @Override
            public void run() {
                Message message = new Message();
                message.obj = bitmapPic;
                handler.sendMessage(message);
            }
        }).start();
      /*  appAction.upload(getUploadString("png", bitmapString), "firstPicture", new CallbackListener<String>() {
            @Override
            public void onSuccess(String data) {
*//*                processLogoUrlWhenAdd(data, isUploadFirst);
                processImageUrlWhenAdd(data, isUploadFirst);
                isUploadFirst = false;
                nullPictureLayout.setVisibility(View.GONE);*//*
                Log.d("test", data);
                if (!TextUtils.isEmpty(data)) {
                    picUrl = data;
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            Message message = new Message();
                            message.obj = new PicUtil().returnBitmap(PropertiesUtil.getImageServer() + picUrl);
                            handler.sendMessage(message);
                        }
                    }).start();
                } else {
                    addPictureImg.setImageResource(R.drawable.ic_add_picture);
                }
            }

            @Override
            public void onFailure(String errorCode, String message) {
                ToastUtil.showShort(IdentifyActivity.this, message);
            }
        });*/
    }

    //
    private void upload(String bitmapString) {
        appAction.upload(getUploadString("png", bitmapString), "firstPicture", new CallbackListener<String>() {
            @Override
            public void onSuccess(String data) {
                if (!TextUtils.isEmpty(data)) {
                    picUrl = PropertiesUtil.getImageServer() + data;
                    Log.d("test", "图片路径" + picUrl);
                    uploadInfo();
                }
            }

            @Override
            public void onFailure(String errorCode, String message) {
                ToastUtil.showShort(IdentifyActivity.this, getResources().getString(R.string.toast_fail_upload));
            }
        });
    }

    //上传
    private void uploadInfo() {
        appAction.realnameAuth(UserInfoKeeper.readPhoneNumber(this), UserInfoKeeper.readRealName(this), idnum, picUrl, "", new CallbackListener<Integer>() {
            @Override
            public void onSuccess(Integer data) {
//                Log.d("test","saf");
                if (data == 0) {
                    ToastUtil.showShort(IdentifyActivity.this, getResources().getString(R.string.toast_success_upload));
                    finish();
//                    uploadBtn.setText(getResources().getString(R.string.txt_upload_again));
                }
            }

            @Override
            public void onFailure(String errorCode, String message) {
                ToastUtil.showShort(IdentifyActivity.this, message);
                messageTxt.setText(getResources().getString(R.string.txt_fail_upload));
            }
        });
    }

    Handler handler = new Handler() {
        @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
        @Override
        public void handleMessage(Message msg) {
            addPictureImg.setImageBitmap((Bitmap) msg.obj);
            super.handleMessage(msg);
        }
    };

    private Bitmap imageZoom(Bitmap bitMap) {
        Log.e("+++++bitmap size big", bitMap.getByteCount() / 1024 + "");
        //图片允许最大空间   单位：KB
        double maxSize = MAX_PIC_SIZE;
        //将bitmap放至数组中，意在bitmap的大小（与实际读取的原文件要大）
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitMap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        byte[] b = baos.toByteArray();
        //将字节换成KB
        double mid = b.length / 1024;
        Log.e("+++++bitmap size", mid + "");
        //判断bitmap占用空间是否大于允许最大空间  如果大于则压缩 小于则不压缩
        if (mid > maxSize) {
            //获取bitmap大小 是允许最大大小的多少倍
            double i = mid / maxSize;
//            Log.e("+++++bitmap i", i+"");
            //开始压缩  此处用到平方根 将宽带和高度压缩掉对应的平方根倍 （1.保持刻度和高度和原bitmap比率一致，压缩后也达到了最大大小占用空间的大小）
            bitMap = zoomImage(bitMap, bitMap.getWidth() / Math.sqrt(i),
                    bitMap.getHeight() / Math.sqrt(i));

        }
        Log.e("+++++bitmap size small", bitMap.getByteCount() / 1024 + "");
        return bitMap;
    }

    public static Bitmap zoomImage(Bitmap bgimage, double newWidth,
                                   double newHeight) {
        // 获取这个图片的宽和高
        float width = bgimage.getWidth();
        float height = bgimage.getHeight();
        // 创建操作图片用的matrix对象
        Matrix matrix = new Matrix();
        // 计算宽高缩放率
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        // 缩放图片动作
        matrix.postScale(scaleWidth, scaleHeight);
        Bitmap bitmap = Bitmap.createBitmap(bgimage, 0, 0, (int) width, (int) height, matrix, true);
        return bitmap;
    }

    private Bitmap getBitmapFromUri(Uri uri) {
        try {
            // 读取uri所在的图片
            Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
            return bitmap;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public byte[] bitmap2Bytes(Bitmap bm) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
        return baos.toByteArray();
    }

    private String getUploadString(String png, String bitmapString) {
        return png + "@" + bitmapString;
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("身份认证页");
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("身份认证页");
        MobclickAgent.onPause(this);
    }
}
